package com.tech.platform.cms.databases.mybatis.sqlParser.tenantParser.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSchemaHandler;
import com.tech.platform.cms.databases.mybatis.sqlParser.tenantParser.TenantContext;
import lombok.Setter;
import lombok.experimental.Accessors;
import net.sf.jsqlparser.schema.Table;

import java.util.Collections;
import java.util.List;

/**
 * @author shengqiang.wu
 * @date 2019/12/26/026 10:49
 * @desc
 */
@Setter
@Accessors(chain = true)
public class TenantTableHandler implements TenantSchemaHandler{

    private List<String> filterTables = Collections.emptyList();

    /**
     * 获取tenant 信息
     * @return
     */
    @Override
    public String getTenantSchema() {
        String tenant = TenantContext.threadLocal.get();
        if(StrUtil.isEmpty(tenant)){
            throw ExceptionUtils.mpe("use tenant strategy,get tenant info error,tenant is null");
        }
        return tenant;
    }

    @Override
    public boolean doTableFilter(String tableName) {
        if(CollUtil.isEmpty(filterTables)){
            return false;
        }

        for (String filterTable : filterTables){
            if(StrUtil.equals(filterTable,tableName)){
                return true;
            }
        }
        return false;
    }

    /**
     * 构建新表名
     * @param table
     */
    public void generatorNewTable(Table table){
        if(!doTableFilter(table.getName())){
            String oriTableName = table.getName();
            String newTableName = oriTableName+"_"+getTenantSchema();
            table.setName(newTableName);
        }
    }
}
